import component from "../Component.js"
import zTreeUtils from "../../experience/utils/zTreeUtils.js";
import {LayerType} from "../../experience/db/SafeMonitorType.js"
import Type from "../../experience/db/Type.js";
import {ServiceType} from "../../experience/db/SafeMonitorType.js";
const Draw = ol.interaction.Draw;
const Style = ol.style.Style;
const Fill = ol.style.Fill;
const Stroke = ol.style.Stroke;
const CircleStyle = ol.style.Circle;
const Feature = ol.Feature;
const Point = ol.geom.Point;
const Icon = ol.style.Icon;
export default class VentilationArrowRender extends component {
    constructor() {
        super()
    }

    async control() {
        this.ztreeUtil = new zTreeUtils()
        this.currentLineFeature = null
        this.currentReadyDeleteVId = ''
        this.currentVentilateType = ''
        this.ventilateList = []
        this.$$('#windDirection').on('click',() => {
            this.ventilayeArrowSet()
        })
        // 创建 选择进风或者回风的弹窗
        this.VentilateTypeDialog = this.app.dialog.create({
            title:'风向类型选择',
            text:'请选择风向类型',
            buttons:[
                {
                    text:'进风',
                    onClick:() => {
                        console.log('进风')
                        this.currentVentilateType = '进风'
                        this.submitVentilateInfo()
                    }
                },
                {
                    text:'回风',
                    onClick:() => {
                        console.log('回风')
                        this.currentVentilateType = '回风'
                        this.submitVentilateInfo()
                    }
                }
            ]
        })
        //
        this.emitter.on('ventilate-animation',() => {
            const ventilate = this.emitter.params[0]
            ventilate.timer = setInterval(this.VentilateTimerAnimation(ventilate),1000)
            this.ventilateList.push(ventilate)
            console.log('this.ventilateList',this.ventilateList)
        })
        this.emitter.on('ventilate-animation-clear',() => {
            this.ventilateList.forEach((ventilate) => {
                clearInterval(ventilate.timer)
            })
            this.ventilateList = []
        })

        this.emitter.on('delete-ventilate', () => {
            this.currentReadyDeleteVId = this.emitter.params[0]
            this.VentilateDeleteDialog = this.app.dialog.confirm('是否删除该风向线','风向系统',this.deleteVentilate.bind(this))
        })

    }

    template() {
        const windDirectionRenderBtn = `<div id="windDirection"  class="GisUtilIcon" style="position: absolute;top: 200px;left: 25px;z-index: 999"><i class="fas fa-wind"></i></div>`
        this.$$("body").append(windDirectionRenderBtn);
        const editStatus = this.utils.getUrlParamer('edit')
            if(editStatus == 'true') {
                this.$$('#windDirection').show()
            }
            else {
                this.$$('#windDirection').hide()
            }

    }
    async deleteVentilate() {
        const ventilateId = this.currentReadyDeleteVId
        const {data} = await this.api.deleteSmVentilate(ServiceType.Mine_Id,'person',ventilateId)
        // 删除结束之后 ，先将本地数据库与远端进行同步
        const ventilations = data.data
        this.db.refresh(LayerType.SMVentilate,ventilations)
        // 重新渲染风向线
        this.drawer._smventilate()
    }

    // 设置风向的函数
    ventilayeArrowSet() {
        const modifySource = this.drawer.source(Type.Modify)
        // 创建画的 gis交互
        const drawInteraction = new Draw({
            source: modifySource,
            type: 'LineString',
            maxPoints:2,
            style: new Style({
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)',
                }),
                stroke: new Stroke({
                    // color: 'rgba(255, 0, 0, 0.5)',
                    color: 'orange',
                    lineDash: [10, 10],
                    width: 2,
                }),
                image: new CircleStyle({
                    radius: 3,
                    stroke: new Stroke({
                        color: 'rgba(255, 0, 0, 0.7)',
                    }),
                    fill: new Fill({
                        color: 'rgba(255, 255, 255, 1)',
                    }),
                }),
            }),
        });
        this.drawInteraction = drawInteraction
        drawInteraction.on('drawend',async (event) => {
            this.VentilateTypeDialog.open()
            this.currentLineFeature = event.feature
        })
        this.drawer.map.addInteraction(drawInteraction)
        // drawInteraction.appendCoordinates([coordinate])

    }

    async submitVentilateInfo() {
        const modifySource = this.drawer.source(Type.Modify)
        const feature = this.currentLineFeature
        const ventilateType = this.currentVentilateType
        const  drawInteraction = this.drawInteraction
        const coordinates = feature.getGeometry().getCoordinates()
        // 转换为cad图纸坐标
        const startPointCoordinate = [this.algo.denormalX(coordinates[0][0]),this.algo.denormalY(coordinates[0][1])]
        const endPointCoordinate =  [this.algo.denormalX(coordinates[1][0]),this.algo.denormalY(coordinates[1][1])]
        this.drawer.map.removeInteraction(drawInteraction)
        const timer = setTimeout(() => {
            modifySource.clear()
            clearTimeout(timer)
        },300)
        const slope = (endPointCoordinate[1] - startPointCoordinate[1]) / (endPointCoordinate[0] - startPointCoordinate[0])
        const rotation = - this.ztreeUtil.get_rel_rotation(endPointCoordinate,startPointCoordinate,slope)
        // const res = await this.api.updateSmVentilateRotation(ServiceType.Mine_Id,'person',ventilate_feature.get('node_id'),rotation)
        const ventilateId = this.ztreeUtil.uuid()
        const {data} = await this.api.addSmVentilate(ServiceType.Mine_Id,'person',ventilateId,rotation,startPointCoordinate[0],startPointCoordinate[1],endPointCoordinate[0],endPointCoordinate[1],ventilateType)
        //先将本地数据库与远端进行同步
        const ventilations = data.data
        this.db.refresh(LayerType.SMVentilate,ventilations)
        // 重新渲染风向线
        this.drawer._smventilate()
    }

    // 由计时器管理的风向动画函数
    VentilateTimerAnimation(ventilate) {
        const {id,start_x,start_y,end_x,end_y,ventilateType} = ventilate
        let src = ''
        if(ventilateType == '进风') {
            src = 'assets/images/safe_monitor/ventilate/icon-arrow-jinfeng.png'
        }
        else {
            src = 'assets/images/safe_monitor/ventilate/icon-arrow-huifeng.png'
        }
        const rotation = Math.atan2(end_y-start_y, end_x-start_x);
        const point = new Point([start_x,start_y])
        const style = new Style({
            // geometry: new Point([start_x,start_y]),
            image: new Icon({
                src: src,
                scale:0.5,
                anchor: [0.75, 0.5],
                rotateWithView: true,
                rotation: -rotation,
            }),
        })
        const feature = new Feature({
            geometry:point,
            // style:style
        })
        feature.setStyle(style)
        feature.set('type',LayerType.SMVentilateAnimation)
        this.drawer.source(LayerType.SMVentilateAnimation).addFeature(feature)
        const step_y = (end_y - start_y) / 10
        const step_x = (end_x - start_x) / 10
        let count = 0
        const geometry = feature.getGeometry()
        return () => {
            if(count < 10) {
                geometry.setCoordinates([start_x + count * step_x,start_y + count * step_y])
            }
            else {
                count = 0
                geometry.setCoordinates([start_x + count * step_x,start_y + count * step_y])
            }
            count++
        }
    }

}

